package main

import (
	"net/http"
	"fmt"
	"os"
	"io/ioutil"
	"github.com/vinkdong/gox/log"
	"gopkg.in/cas.v1"
)

func CasCheck(w http.ResponseWriter, r *http.Request) bool {
	ticket := r.FormValue("ticket")

	if ticket == "" {
		return false
	}

	casUrl := os.Getenv("CAS_URL")

	service := fmt.Sprintf("http://%s%s",r.Host,r.URL.Path)
	client := &http.Client{}

	validateUrl := fmt.Sprintf("%s%s",casUrl,"serviceValidate")

	req, err := http.NewRequest("GET",validateUrl,nil)

	if err != nil {
		log.Error(err)
	}

	q:= req.URL.Query()
	q.Add("ticket",ticket)
	q.Add("service",service)

	req.URL.RawQuery = q.Encode()

	resp , err := client.Do(req)

	if err != nil{
		log.Error(err)
	}

	defer resp.Body.Close()
	respBody, _ := ioutil.ReadAll(resp.Body)

	authenticationResponse, err :=  cas.ParseServiceResponse(respBody)

	if err !=nil{
		log.Error(err)
	}

	if authenticationResponse != nil{

		c,err  := r.Cookie("_cas_session")
		if err != nil{
			log.Error(err)
		}
		if c != nil{
			validateCookies[cr] = c.Value
		}

		if cr >= 99990{
			cr = 0
		}else {
			cr += 1
		}
		return true

	}
	return false
}
